package com.sport.app;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.google.zxing.client.android.CaptureActivity;
import com.sport.app.alipay.AuthResult;
import com.sport.app.alipay.PayResult;
import com.sport.app.base.BaseActivity;
import com.sport.app.bean.WxPayOrderBean;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tencent.smtt.utils.TbsLog;

import java.net.URISyntaxException;
import java.util.Map;

import static com.sport.app.bean.Constants.NEXT_PAGE;
import static com.sport.app.bean.Constants.TAB0;
import static com.sport.app.bean.Constants.TAB1;
import static com.sport.app.bean.Constants.TAB2;
import static com.sport.app.bean.Constants.TAB3;

public class VFlyX5Activity extends BaseActivity {
    private final static String TAG = VFlyX5Activity.class.getSimpleName();
    private static final int SDK_AUTH_FLAG = 2;
    private static final int SDK_PAY_FLAG = 1;
    private static final int PERMISSIONS_REQUEST_CODE = 1002;
    private static final int SCAN_REQUEST_CODE = 100;
    private static final int CAMERA_PERMISSION = 110;
    private static final String BASEURL = "https://member.vfly.test.qianchengtech.com/#/login";
    private com.tencent.smtt.sdk.WebView mWebView;
    private LoadingDialog mLoadingDialog;
    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;
    private String mCurrentUrl = null;
    private IWXAPI api;
    private long firstTime = 0;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
//                    mWebView.reload();
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        showToast("支付成功", Toast.LENGTH_SHORT);

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        showToast("支付失败", Toast.LENGTH_SHORT);
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        showToast("授权成功", Toast.LENGTH_SHORT);
                    } else {
                        // 其他状态值则为授权失败
                        showToast("授权失败", Toast.LENGTH_SHORT);
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vfly_x5);
        mWebView = findViewById(R.id.x5webview);
        mLoadingDialog = new LoadingDialog(this, R.style.CustomDialog);
        mWebView.setWebChromeClient(new WebChromeClient() {
            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                Log.i(TAG, "openFileChooser 1");
                VFlyX5Activity.this.uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsgs) {
                Log.i(TAG, "openFileChooser 2");
                VFlyX5Activity.this.uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android  > 4.1.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                Log.i(TAG, "openFileChooser 3");
                VFlyX5Activity.this.uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android  >= 5.0
            public boolean onShowFileChooser(com.tencent.smtt.sdk.WebView webView,
                                             ValueCallback<Uri[]> filePathCallback,
                                             WebChromeClient.FileChooserParams fileChooserParams) {
                Log.i(TAG, "openFileChooser 4:" + filePathCallback.toString());
                VFlyX5Activity.this.uploadFiles = filePathCallback;
                openFileChooseProcess();
                return true;
            }

            @Override
            public boolean onJsAlert(WebView webView, String s, String s1, JsResult jsResult) {
                return super.onJsAlert(webView, s, s1, jsResult);
            }
        });
        init();
        requestPermission();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    if (null != uploadFile) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFile.onReceiveValue(result);
                        uploadFile = null;
                    }
                    if (null != uploadFiles) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFiles.onReceiveValue(new Uri[]{result});
                        uploadFiles = null;
                    }
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (null != uploadFile) {
                uploadFile.onReceiveValue(null);
                uploadFile = null;
            }
        }

        if (resultCode == RESULT_OK) {
            if (requestCode == SCAN_REQUEST_CODE) {
                //Todo Handle the isbn number entered manually
                String isbn = data.getStringExtra("CaptureIsbn");
                if (!TextUtils.isEmpty(isbn)) {
                    //todo something
                    if (isbn.contains("protocol")) {
                        mWebView.loadUrl(isbn);
                    } else {
                        showToast("无效内容", Toast.LENGTH_SHORT);
                    }
                }
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //重写onKeyDown，当浏览网页，WebView可以后退时执行后退操作。
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime < 2000) {
                System.exit(0);
            } else {
                Toast.makeText(VFlyX5Activity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    //销毁Webview
    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();
            mWebView.clearCache(true);
            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }

    private void openFileChooseProcess() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        startActivityForResult(Intent.createChooser(intent, "vfly"), 0);
    }

    private void init() {
        mLoadingDialog.show();
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
                super.onPageStarted(webView, s, bitmap);
                if (!mLoadingDialog.isShowing())
                    mLoadingDialog.show();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains("next=/")) {
                    mWebView.stopLoading();
                    if (url.contains("back") && mWebView.canGoBack()) {
                        mWebView.goBack();
                    } else {
                        int length = url.lastIndexOf("/");
                        mWebView.loadUrl(NEXT_PAGE + url.substring(length));
                    }
                }

                if (url.contains("msgBox=alert")) {
                    mWebView.stopLoading();
                    int length = url.indexOf("content=");
                    String msg = url.substring(length + "content=".length());
                    try {
                        String result = new java.net.URI(msg).getPath();
                        WebviewDialog webviewDialog = new WebviewDialog(VFlyX5Activity.this, result);
                        webviewDialog.setOnclickLister(new WebviewDialog.Listener() {
                            @Override
                            public void onFinish() {
                                if (mWebView.getUrl().contains("my")) {
                                    mWebView.reload();
                                }
                            }
                        });
                        webviewDialog.show(getSupportFragmentManager(), "tag");
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }

                }

                if (url.contains("msgBox=confirm")) {
                    mWebView.stopLoading();
                    int length = url.indexOf("content=");
                    String msg = url.substring(length + "content=".length());
                    try {
                        String result = new java.net.URI(msg).getPath();
                        ConfirmDialog confirmDialog = new ConfirmDialog(VFlyX5Activity.this, result);
                        confirmDialog.setOnclickLister(new ConfirmDialog.Listener() {
                            @Override
                            public void onConfirm() {
                                if (mWebView.getUrl().contains("order")) {
                                    mWebView.loadUrl("javascript:ticketRefund()");
                                }
                            }
                        });
                        confirmDialog.show(getSupportFragmentManager(), "tag");
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }

                }

                if (url.contains("next=scanQr")) {
                    mWebView.stopLoading();
                    startScanActivity();
                }

                if (url.contains("alipay_sdk")) {
                    mWebView.stopLoading();
                    mWebView.reload();
                    int length = url.indexOf("alipay_sdk");
                    String payInfo = url.substring(length);
                    aliPayNative(payInfo);
                }

                if (url.contains("pay=7&ticket")) {
                    mWebView.stopLoading();
                    mWebView.reload();
                    int length = url.indexOf("{");
                    String payInfo = url.substring(length);
                    wxPay(payInfo);
                }
                if ((url.startsWith("http://") || url.startsWith("https://"))) {
                    view.loadUrl(url);
                    mWebView.stopLoading();
                    return true;
                }
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (TextUtils.equals(TAB0, url) ||
                        TextUtils.equals(TAB1, url) ||
                        TextUtils.equals(TAB2, url) ||
                        TextUtils.equals(TAB3, url)) {
                    mWebView.clearHistory();
                }
                mLoadingDialog.dismiss();
                mCurrentUrl = url;
            }
        });

        WebSettings webSetting = mWebView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
//        mWebView.setScrollContainer(false);
//        mWebView.setVerticalScrollBarEnabled(false);
//        mWebView.setHorizontalScrollBarEnabled(false);
//        mWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY) ;
//        mWebView.setScrollbarFadingEnabled(true);
        webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
//         webSetting.setPreFectch(true);
        long time = System.currentTimeMillis();
        mWebView.loadUrl(BASEURL);
        TbsLog.d("time-cost", "cost time: "
                + (System.currentTimeMillis() - time));
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();
    }

    /**
     * 检查支付宝 SDK 所需的权限，并在必要的时候动态获取。
     * 在 targetSDK = 23 以上，READ_PHONE_STATE 和 WRITE_EXTERNAL_STORAGE 权限需要应用在运行时获取。
     * 如果接入支付宝 SDK 的应用 targetSdk 在 23 以下，可以省略这个步骤。
     */
    private void requestPermission() {
        // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{
                            Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.CAMERA
                    }, PERMISSIONS_REQUEST_CODE);

        }
    }

    /**
     * ********************************************************************************************
     * 支付调用android的方法
     * ********************************************************************************************
     */
    private void aliPayNative(final String orderInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask((VFlyX5Activity.this));
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void wxPay(final String orderInfo) {
        Gson gson = new Gson();
        WxPayOrderBean wxPayOrderBean = gson.fromJson(orderInfo, WxPayOrderBean.class);
        api = WXAPIFactory.createWXAPI(this, wxPayOrderBean.appid);
        PayReq req = new PayReq();
        req.appId = wxPayOrderBean.appid;
        req.partnerId = wxPayOrderBean.partnerid;
        req.prepayId = wxPayOrderBean.prepayid;
        req.nonceStr = wxPayOrderBean.noncestr;
        req.timeStamp = wxPayOrderBean.timestamp + "";
        req.packageValue = wxPayOrderBean.packageX;
        req.sign = wxPayOrderBean.sign;
        api.sendReq(req);
    }

    //
    private void startScanActivity() {
        Intent intent = new Intent(VFlyX5Activity.this, CaptureActivity.class);
        startActivityForResult(intent, SCAN_REQUEST_CODE);
    }
}
